package com.ruoyi.controller;

import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.domain.RecoverStation;
import com.ruoyi.domain.vo.ArticleColumnVo;
import com.ruoyi.domain.vo.ArticleOriginDateVo;
import com.ruoyi.domain.vo.DeptArticleCountVo;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.mapper.ArticleMapper;
import com.ruoyi.mapper.RecoverStationMapper;
import com.ruoyi.service.impl.PdfParseTaskServiceImpl;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.sun.xml.bind.v2.TODO;
import org.apache.catalina.User;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.domain.Article;
import com.ruoyi.service.ArticleService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * articleController
 *
 * @author ruoyi
 * @date 2025-01-16
 */
@RestController
@RequestMapping("/article/article")
public class ArticleController extends BaseController
{
    @Autowired
    private ArticleService articleService;
    @Autowired
    private PdfParseTaskServiceImpl pdfParseTaskService;
    @Value("${ruoyi.profile}")
    private String filePath;
    @Autowired
    private FileStorageService fileStorageService;//注入实列

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private RecoverStationMapper recoverStationMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;



    /**
     * 判断部门是否直接隶属于荆州市长江河道管理局（一级子部门）
     * @param dept 部门信息
     * @param sysDeptMapper 部门Mapper
     * @return 是否直接隶属于荆州市长江河道管理局
     */
    private static boolean isDirectSubDeptOfJingZhou(SysDept dept, SysDeptMapper sysDeptMapper) {
        // 如果部门本身就是"荆州市长江河道管理局"，则不认为是其下级部门
        if ("荆州市长江河道管理局".equals(dept.getDeptName())) {
            return false;
        }
        
        // 直接检查父部门是否为"荆州市长江河道管理局"
        // 如果父部门ID有效，直接查询父部门名称
        if (dept.getParentId() != null && dept.getParentId() > 0) {
            SysDept parentDept = sysDeptMapper.selectDeptById(dept.getParentId());
            if (parentDept != null && "荆州市长江河道管理局".equals(parentDept.getDeptName())) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * 获取所有部门列表（市局/总局和直接隶属于荆州市长江河道管理局的部门）
     */
    @Anonymous
    @GetMapping("/deptList")
    public AjaxResult getDeptList() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();
        String userName = sysUser.getUserName();
        
        // 查询所有部门
        List<SysDept> depts = sysDeptMapper.selectDeptList(new SysDept());
        List<Map<String, String>> deptList = new ArrayList<>();
        
        // 对于admin用户，返回市局/总局和所有分局
        if ("admin".equals(userName)) {
            for (SysDept dept : depts) {
                // 添加市局/总局
                if ("市局/总局".equals(dept.getDeptName())) {
                    Map<String, String> deptMap = new HashMap<>();
                    deptMap.put("value", dept.getDeptName());
                    deptMap.put("label", dept.getDeptName());
                    deptList.add(deptMap);
                }
                // 添加直接隶属于荆州市长江河道管理局的部门（分局）
                else if (dept.getDeptName() != null && 
                         isDirectSubDeptOfJingZhou(dept, sysDeptMapper)) {
                    Map<String, String> deptMap = new HashMap<>();
                    deptMap.put("value", dept.getDeptName());
                    deptMap.put("label", dept.getDeptName());
                    deptList.add(deptMap);
                }
            }
        } else {
            // 对于其他用户，保持原有逻辑
            for (SysDept dept : depts) {
                // 排除市局/总局及其子部门
                if (dept.getDeptName() != null && 
                    !"市局/总局".equals(dept.getDeptName()) && 
                    !isCityBureauOrSubordinate(dept) &&
                    isDirectSubDeptOfJingZhou(dept, sysDeptMapper)) {
                    Map<String, String> deptMap = new HashMap<>();
                    deptMap.put("value", dept.getDeptName());
                    deptMap.put("label", dept.getDeptName());
                    deptList.add(deptMap);
                }
            }
        }
        
        return AjaxResult.success(deptList);
    }
    
    /**
     * 判断部门是否为市局/总局或其子部门
     * @param dept 部门信息
     * @return 是否为市局/总局或其子部门
     */
    private boolean isCityBureauOrSubordinate(SysDept dept) {
        if (dept == null) {
            return false;
        }
        
        // 如果当前部门就是市局/总局，直接返回true
        if ("市局/总局".equals(dept.getDeptName())) {
            return true;
        }
        
        // 通过祖先部门查找是否属于市局/总局
        String ancestors = dept.getAncestors();
        if (ancestors != null && !ancestors.isEmpty()) {
            // 从 ancestors 中提取所有祖先部门ID
            String[] ancestorIds = ancestors.split(",");
            
            // 查询祖先部门中是否有市局/总局
            for (String ancestorId : ancestorIds) {
                if (!ancestorId.trim().isEmpty()) {
                    try {
                        Long deptId = Long.parseLong(ancestorId.trim());
                        SysDept ancestorDept = sysDeptMapper.selectDeptById(deptId);
                        if (ancestorDept != null && "市局/总局".equals(ancestorDept.getDeptName())) {
                            return true;
                        }
                    } catch (NumberFormatException e) {
                        // 忽略无效ID
                    }
                }
            }
        }
        
        return false;
    }
    
    /**
     * 获取用户权限信息
     */
    @Anonymous
    @GetMapping("/userPermission")
    public AjaxResult getUserPermission() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();
        String userName = sysUser.getUserName();
        
        // 获取用户所属部门
        String userDeptName = null;
        if (sysUser.getDept() != null) {
            userDeptName = sysUser.getDept().getDeptName();
        }
        
        // 获取用户所属的分局名称
        String userDeptOrigin = null;
        if (sysUser.getDept() != null) {
            userDeptOrigin = getDeptArticleOrigin(sysUser);
        }
        
        // 判断用户是否可以选分局
        boolean canSelectDept = false;
        
        // admin用户可以选分局
        if ("admin".equals(userName)) {
            canSelectDept = true;
        }
        // 市局/总局用户可以选分局
        else if (userDeptName != null && "市局/总局".equals(userDeptName)) {
            canSelectDept = true;
        }
        // 市局/总局的子部门用户也可以选分局
        else if (sysUser.getDept() != null && isCityBureauOrSubordinate(sysUser)) {
            canSelectDept = true;
        }
        // 直接隶属于荆州市长江河道管理局的部门（包括分局及其子部门）用户不能选分局
        else if (sysUser.getDept() != null && isDirectSubDeptOfJingZhou(sysUser.getDept(), sysDeptMapper)) {
            canSelectDept = false;
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("canSelectDept", canSelectDept);
        result.put("userDept", userDeptName);
        result.put("userDeptOrigin", userDeptOrigin);
        result.put("userName", userName);
        
        return AjaxResult.success(result);
    }

    /**
     * 日期区间查询对应分局的不同栏目文章数量
     */
    @Anonymous
    @GetMapping("/articleCountByColumn")
    public TableDataInfo selectArticleCountByColumn(@RequestParam("startTime") String startTime,
                                                    @RequestParam("endTime") String endTime,
                                                    @RequestParam(value = "deptName", required = false) String deptName)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();
        String userName = sysUser.getUserName();
        System.out.println("开始时间"+startTime);
        System.out.println("结束时间"+endTime);
        
        // 获取用户所属部门
        String userDeptName = null;
        if (sysUser.getDept() != null) {
            userDeptName = sysUser.getDept().getDeptName();
        }
        
        System.out.println("用户部门: " + userDeptName);
        
        List<ArticleColumnVo> list;
        
        // 根据部门类型决定查询方式
        if (deptName != null && !deptName.isEmpty()) {
            // 如果前端指定了部门名称，需要判断这个部门是否是分局
            // 如果是分局，则按该分局及其子部门查询；如果不是分局，则直接按该部门查询
            String articleOrigin = getDeptArticleOriginByName(deptName);
            if (articleOrigin != null) {
                // 指定的部门是分局或其子部门，按所属分局及其子部门查询
                list = articleService.selectArticleColumnListByDeptAndSubDepts(articleOrigin, startTime, endTime);
            } else {
                // 指定的部门不是分局体系中的部门，直接按该部门查询
                list = articleService.selectArticleColumnListByDeptAndSubDepts(deptName, startTime, endTime);
            }
        } else if ("admin".equals(userName)) {
            // 如果是admin用户，且没有选择具体分局，则查询所有数据
            list = articleService.selectAllDeptArticleColumnList(startTime, endTime);
        } else if (userDeptName != null && isCityBureauOrSubordinate(sysUser)) {
            // 如果是市局用户或其子部门，且没有选择具体分局，则按市局及其所有子部门查询
            String cityBureauName = getCityBureauName(sysUser);
            if (cityBureauName != null) {
                list = articleService.selectArticleColumnListByDeptAndSubDepts(cityBureauName, startTime, endTime);
            } else {
                list = articleService.selectArticleColumnListByDeptAndSubDepts(userDeptName, startTime, endTime);
            }
        } else if (sysUser.getDept() != null && isDirectSubDeptOfJingZhou(sysUser.getDept(), sysDeptMapper)) {
            // 如果是直接隶属于荆州市长江河道管理局的部门用户（包括分局及其子部门），按所属分局及其子部门查询
            String articleOrigin = getDeptArticleOrigin(sysUser);
            if (articleOrigin != null) {
                list = articleService.selectArticleColumnListByDeptAndSubDepts(articleOrigin, startTime, endTime);
            } else {
                list = articleService.selectArticleColumnListByDeptAndSubDepts(userDeptName, startTime, endTime);
            }
        } else {
            // 其他情况（包括直接隶属于荆州市长江河道管理局的部门的子部门等），通过祖先部门查找所属部门
            String articleOrigin = getDeptArticleOrigin(sysUser);
            if (articleOrigin != null && isDirectSubDeptOfJingZhou(sysUser.getDept(), sysDeptMapper)) {
                // 如果祖先部门是直接隶属于荆州市长江河道管理局的部门，则按该部门及其子部门查询
                list = articleService.selectArticleColumnListByDeptAndSubDepts(articleOrigin, startTime, endTime);
            } else {
                // 否则按原有逻辑查询
                list = articleService.selectArticleColumnList(userName, startTime, endTime);
            }
        }
        
        return getDataTable(list);
    }
    
    /**
     * 获取用户部门对应的文章来源（直接隶属于荆州市长江河道管理局的部门名称）
     * 通过祖先部门查找所属的直接隶属于荆州市长江河道管理局的部门
     */
    private String getDeptArticleOrigin(SysUser sysUser) {
        if (sysUser.getDept() == null) {
            return null;
        }
        
        // 直接通过getDirectSubDeptOfJingZhou方法获取所属的直接隶属于荆州市长江河道管理局的部门
        return getDirectSubDeptOfJingZhou(sysUser.getDept(), sysDeptMapper);
    }
    
    /**
     * 根据部门名称获取其所属的直接隶属于荆州市长江河道管理局的部门（分局）
     * @param deptName 部门名称
     * @return 所属分局名称
     */
    private String getDeptArticleOriginByName(String deptName) {
        if (deptName == null || deptName.isEmpty()) {
            return null;
        }
        
        // 首先根据部门名称获取部门信息
        SysDept dept = sysDeptMapper.selectDeptByName(deptName);
        if (dept == null) {
            return null;
        }
        
        // 直接通过getDirectSubDeptOfJingZhou方法获取所属的直接隶属于荆州市长江河道管理局的部门
        return getDirectSubDeptOfJingZhou(dept, sysDeptMapper);
    }
    
    /**
     * 获取部门所属的直接隶属于荆州市长江河道管理局的部门（分局）
     * @param dept 部门信息
     * @param sysDeptMapper 部门Mapper
     * @return 所属分局名称
     */
    private String getDirectSubDeptOfJingZhou(SysDept dept, SysDeptMapper sysDeptMapper) {
        if (dept == null) {
            return null;
        }
        
        // 如果该部门直接隶属于荆州市长江河道管理局，直接返回该部门名称
        if (isDirectSubDeptOfJingZhou(dept, sysDeptMapper)) {
            return dept.getDeptName();
        }
        
        // 否则通过祖先部门查找
        String ancestors = dept.getAncestors();
        if (ancestors != null && !ancestors.isEmpty()) {
            // 从 ancestors 中提取所有祖先部门ID
            String[] ancestorIds = ancestors.split(",");
            
            // 从后往前查找（越靠近自己越优先），找到直接隶属于荆州市长江河道管理局的部门
            for (int i = ancestorIds.length - 1; i >= 0; i--) {
                String ancestorId = ancestorIds[i];
                if (!ancestorId.trim().isEmpty()) {
                    try {
                        Long deptId = Long.parseLong(ancestorId.trim());
                        SysDept ancestorDept = sysDeptMapper.selectDeptById(deptId);
                        // 检查祖先部门是否直接隶属于荆州市长江河道管理局
                        if (ancestorDept != null && ancestorDept.getDeptName() != null &&
                                isDirectSubDeptOfJingZhou(ancestorDept, sysDeptMapper)) {
                            return ancestorDept.getDeptName();
                        }
                    } catch (NumberFormatException e) {
                        // 忽略无效ID
                    }
                }
            }
        }
        
        return null;
    }
    
    /**
     * 判断用户是否属于市局或其子部门
     */
    private boolean isCityBureauOrSubordinate(SysUser sysUser) {
        if (sysUser.getDept() == null) {
            return false;
        }
        
        // 如果当前部门就是市局/总局，直接返回true
        String currentDeptName = sysUser.getDept().getDeptName();
        if (currentDeptName != null && "市局/总局".equals(currentDeptName)) {
            return true;
        }
        
        // 通过祖先部门查找是否属于市局/总局
        String ancestors = sysUser.getDept().getAncestors();
        if (ancestors != null && !ancestors.isEmpty()) {
            // 从 ancestors 中提取所有祖先部门ID
            String[] ancestorIds = ancestors.split(",");
            
            // 查询祖先部门中是否有市局/总局
            for (String ancestorId : ancestorIds) {
                if (!ancestorId.trim().isEmpty()) {
                    try {
                        Long deptId = Long.parseLong(ancestorId.trim());
                        SysDept ancestorDept = sysDeptMapper.selectDeptById(deptId);
                        if (ancestorDept != null) {
                            if ("市局/总局".equals(ancestorDept.getDeptName())) {
                                return true;
                            }
                        }
                    } catch (NumberFormatException e) {
                        // 忽略无效ID
                    }
                }
            }
        }
        
        return false;
    }
    
    /**
     * 获取市局部门名称
     */
    private String getCityBureauName(SysUser sysUser) {
        if (sysUser.getDept() == null) {
            return null;
        }
        
        // 如果当前部门就是市局/总局，直接返回
        String currentDeptName = sysUser.getDept().getDeptName();
        if (currentDeptName != null && "市局/总局".equals(currentDeptName)) {
            return currentDeptName;
        }
        
        // 通过祖先部门查找市局/总局
        String ancestors = sysUser.getDept().getAncestors();
        if (ancestors != null && !ancestors.isEmpty()) {
            // 从 ancestors 中提取所有祖先部门ID
            String[] ancestorIds = ancestors.split(",");
            
            // 查询祖先部门中是否有市局/总局
            for (String ancestorId : ancestorIds) {
                if (!ancestorId.trim().isEmpty()) {
                    try {
                        Long deptId = Long.parseLong(ancestorId.trim());
                        SysDept ancestorDept = sysDeptMapper.selectDeptById(deptId);
                        if (ancestorDept != null) {
                            if ("市局/总局".equals(ancestorDept.getDeptName())) {
                                return ancestorDept.getDeptName();
                            }
                        }
                    } catch (NumberFormatException e) {
                        // 忽略无效ID
                    }
                }
            }
        }
        
        return null;
    }


    /**
     * 日期区间查询
     */
    @Anonymous
    @GetMapping("/articleOriginDateCount")
    public TableDataInfo selectArticleOriginDateCount(@RequestParam(value = "startTime", defaultValue = "") String startTime,
                                                      @RequestParam(value = "endTime", defaultValue = "") String endTime) {


        List<ArticleOriginDateVo> list = articleService.selectArticleOriginDateList(startTime,endTime);
        return getDataTable(list);
    }

    /**
     * 按部门统计文章数量
     */
    @Anonymous
    @GetMapping("/deptArticleCount")
    public TableDataInfo selectDeptArticleCount(@RequestParam(value = "startTime", defaultValue = "") String startTime,
                                                @RequestParam(value = "endTime", defaultValue = "") String endTime) {
        // 权限检查：只有admin用户和市局/总局用户可以访问
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();
        String userName = sysUser.getUserName();
        String deptName = sysUser.getDept() != null ? sysUser.getDept().getDeptName() : null;

        boolean hasPermission = "admin".equals(userName) ||
                               (deptName != null && "市局/总局".equals(deptName)) ||
                               (sysUser.getDept() != null && isCityBureauOrSubordinate(sysUser));

        if (!hasPermission) {
            // 如果没有权限，返回空列表
            return getDataTable(new ArrayList<>());
        }

        List<DeptArticleCountVo> list = articleService.selectDeptArticleCountList(startTime, endTime);
        return getDataTable(list);
    }

    /**
     * 审核表路径
     */
    @Anonymous
    @PostMapping("/appvalPath/{id}")
    public AjaxResult appvalPath(@PathVariable Long id, @RequestParam("appvalPath") MultipartFile appvalPath) throws Exception {
        try {
            // 检查文件是否为空
            if (appvalPath.isEmpty()) {
                return AjaxResult.error("上传文件为空");
            }

            // 获取 base-path
            String basePath = "articleFilePath/appvalPath/";

            // 指定oss保存文件路径
            String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/" + appvalPath.getOriginalFilename();
            // 上传图片，成功返回文件信息
            FileInfo fileInfo = fileStorageService.of(appvalPath).setPath(objectName).upload();

            // 设置返回结果
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileInfo.getUrl());
            ajax.put("fileName", fileInfo.getUrl());
            ajax.put("newFileName", fileInfo.getUrl());
            ajax.put("originalFilename", appvalPath.getOriginalFilename());

            // 创建Article对象并设置ID和filePath
            Article article = new Article();
            article.setArticleId(id);
            article.setAppval(fileInfo.getUrl());

            // 更新数据库中的filePath字段
            articleService.updateById(article);

            return ajax;

        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 文章内容图片上传
     */
    @Anonymous
    @PostMapping("/contentImage")
    public AjaxResult uploadContentImage(@RequestParam("file") MultipartFile file) throws Exception {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件为空");
            }

            // 获取 base-path
            String basePath = "articleFilePath/contentImage/";

            // 指定oss保存文件路径
            String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/" + file.getOriginalFilename();
            // 上传图片，成功返回文件信息
            FileInfo fileInfo = fileStorageService.of(file).setPath(objectName).upload();

            // 设置返回结果
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileInfo.getUrl());
            ajax.put("fileName", fileInfo.getUrl());
            ajax.put("newFileName", fileInfo.getUrl());
            ajax.put("originalFilename", file.getOriginalFilename());

            return ajax;

        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 封面路径
     */
    @Anonymous
    @PostMapping("/filePath/{id}")
    public AjaxResult uploadFile(@PathVariable Long id, @RequestParam MultipartFile file) throws Exception {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件为空");
            }

            // 获取 base-path
            String basePath = "articleFilePath/filePath/"; // 直接在这里设置基础路径，或者从配置文件中读取

            // 指定oss保存文件路径
            String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/" + file.getOriginalFilename();
            // 上传图片，成功返回文件信息
            FileInfo fileInfo = fileStorageService.of(file).setPath(objectName).upload();

            // 设置返回结果
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileInfo.getUrl());
            ajax.put("fileName", fileInfo.getUrl());
            ajax.put("newFileName", fileInfo.getUrl());
            ajax.put("originalFilename", file.getOriginalFilename());

            // 创建Article对象并设置ID和filePath
            Article article = new Article();
            article.setArticleId(id);
            article.setCoverPath(fileInfo.getUrl());
            System.out.printf("封面路径："+fileInfo.getUrl());

            // 更新数据库中的filePath字段
            articleMapper.updateArticle(article);

            return ajax;

        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 附件上传
     */
    @Anonymous
    @PostMapping("/attachment/{id}")
    public AjaxResult uploadAttachment(@PathVariable Long id, @RequestParam MultipartFile file) throws Exception {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件为空");
            }

            // 获取 base-path
            String basePath = "articleFilePath/attachment/";

            // 指定oss保存文件路径
            String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/" + file.getOriginalFilename();
            // 上传文件，成功返回文件信息
            FileInfo fileInfo = fileStorageService.of(file).setPath(objectName).upload();

            // 设置返回结果
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileInfo.getUrl());
            ajax.put("fileName", fileInfo.getUrl());
            ajax.put("newFileName", fileInfo.getUrl());
            ajax.put("originalFilename", file.getOriginalFilename());

            // 先查询完整的Article对象
            Article article = articleService.selectArticleByArticleId(id);
            if (article != null) {
                // 更新attachment字段
                article.setAttachment(fileInfo.getUrl());
                // 更新数据库中的attachment字段
                articleMapper.updateArticle(article);
            }

            System.out.println("文章附件："+fileInfo.getUrl());

            return ajax;

        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    
    
// ... 其他现有代码 ...

    /**
     * 根据column_id查询
     */
//    @PreAuthorize("@ss.hasPermi('article:article:getOneByColumnId')")
    @GetMapping("/getListByColumnId")
    public AjaxResult getListByColumnId(@RequestParam("column_id") Integer columnId,
                                        @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        if (Objects.isNull(columnId)) {
            return error("未知参数");
        }

        // 启用分页
        PageHelper.startPage(pageNum, pageSize);

        // 查询数据列表
        List<Article> articleList = articleService.query()
                .eq("column_id", columnId)
                .orderByDesc("pubdate")
                .list();

        // 用PageInfo对结果进行包装
        PageInfo<Article> pageInfo = new PageInfo<>(articleList);

        // 返回分页结果，包含total等信息
        return success(pageInfo);
    }
    /**
     * 查询article列表(权限版)
     */
    @GetMapping("/list")
    public Map<String, Object> list(Article article){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();

        String userName=sysUser.getUserName();

        String dept = sysUser.getDept().getDeptName();

        // 判断是否为管理员账户
        boolean isSuperAdmin = "admin".equals(userName);

        boolean hasManagerPermission = isSuperAdmin;

        // 如果不是超级管理员，则检查部门权限
        if (!isSuperAdmin && sysUser.getDept() != null) {
            // 获取用户所属部门
            String deptName = sysUser.getDept().getDeptName();

            // 根据部门层级关系判断权限：
            if (deptName != null) {
                if ("市局/总局".equals(deptName)) {
                    // 市局/总局具有管理权限
                    hasManagerPermission = true;
                } else if (isDirectSubDeptOfJingZhou(sysUser.getDept(), sysDeptMapper)) {
                    // 直接隶属于荆州市长江河道管理局的部门（分局）不具有管理权限
                    hasManagerPermission = false;
                } else {
                    // 其他部门，通过 ancestors 字段判断是否属于市局/总局的下级部门
                    String ancestors = sysUser.getDept().getAncestors();
                    if (ancestors != null && !ancestors.isEmpty()) {
                        // 从 ancestors 中提取所有祖先部门ID
                        String[] ancestorIds = ancestors.split(",");

                        // 查询祖先部门中是否有市局/总局
                        boolean foundManagerDept = false;
                        for (String ancestorId : ancestorIds) {
                            if (!ancestorId.trim().isEmpty()) {
                                try {
                                    Long deptId = Long.parseLong(ancestorId.trim());
                                    SysDept ancestorDept = sysDeptMapper.selectDeptById(deptId);
                                    if (ancestorDept != null && "市局/总局".equals(ancestorDept.getDeptName())) {
                                        foundManagerDept = true;
                                        break;
                                    }
                                } catch (NumberFormatException e) {
                                    // 忽略无效ID
                                }
                            }
                        }
                        hasManagerPermission = foundManagerDept;
                    } else {
                        hasManagerPermission = false;
                    }
                }
            }
        }

        startPage();
        List<Article> list = articleService.selectArticleListByRole(hasManagerPermission, article);
        TableDataInfo tableDataInfo = getDataTable(list);
        HashMap<String, Object> result = new HashMap<>();
        result.put("data", tableDataInfo);
        result.put("canAdd", hasManagerPermission);
        result.put("userName", userName);
        result.put("dept", dept);

        return result;
    }

    /**
     * 查询article列表
     */
//    @PreAuthorize("@ss.hasPermi('article:article:list')")
    @Anonymous
    @GetMapping("/list1")
    public TableDataInfo list1(Article article)
    {
//        startPage();
        List<Article> list = articleService.selectArticleList(article);
        return getDataTable(list);
    }

    /**
     * 导出article列表
     */
    @PreAuthorize("@ss.hasPermi('article:article:export')")
    @Log(title = "article", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Article article)
    {
        List<Article> list = articleService.selectArticleList(article);
        ExcelUtil<Article> util = new ExcelUtil<Article>(Article.class);
        util.exportExcel(response, list, "article数据");
    }

    /**
     * 获取article详细信息
     */
//    @PreAuthorize("@ss.hasPermi('article:article:query')")
    @Anonymous
    @GetMapping(value = "/{articleId}")
    public AjaxResult getInfo(@PathVariable("articleId") Long articleId)
    {
        return success(articleService.selectArticleByArticleId(articleId));
    }

    /**
     * 新增article
     */
    @PreAuthorize("@ss.hasPermi('article:article:add')")
    @Log(title = "article", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Article article,@RequestParam String articleName)
    {
        if(Objects.isNull(article)){
            return error("请将数据填充完整");
        }

        // 检查是否上传了审批表
        if (article.getAppval() == null || article.getAppval().isEmpty()) {
            return error("请上传审批表");
        }

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();
        String userName=sysUser.getUserName();
        //得到登录用户属于的部门
        String deptName = sysUser.getDept().getDeptName();
        //得到现在的时间然后设置pubdate
        // 获取当前日期并格式化为字符串
        LocalDate now = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String currentDate = now.format(formatter);

// 设置到article对象中
        article.setPubdate(currentDate);





        //获取用户ip地址
        String ip = sysUser.getLoginIp();
        //System.out.println("目前用户的ip:"+ ip);
        article.setIp(ip);
        //article.setAuthor(userName);
        //article.setArticleOrigin(deptName);
        return toAjax(articleService.insertArticle(article,articleName));
    }

    /**
     * 修改article
     */
    @PreAuthorize("@ss.hasPermi('article:article:edit')")
    @Log(title = "article", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Article article,@RequestParam String articleName)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();
        String userName=sysUser.getUserName();
        String ip=sysUser.getLoginIp();
        // 不再强制设置author为当前用户名，使用前端传递的值
        article.setIp(ip);
        return toAjax(articleService.updateArticle(article,articleName));
    }

//    @GetMapping("/getUsernameByIdAndIp")
//    public AjaxResult getUsernameByIdAndIp(@RequestParam Long userId,
//                                           @RequestParam String ip) {
//        if (userId == null || ip == null) {
//            return error("参数缺失");
//        }
//
//        SysUser user = sysUserMapper.selectUserByIdAndIp(userId, ip);
//
//        if (user != null) {
//            return success(user.getUserName());
//        } else {
//            return success("用户不存在或IP不匹配");
//        }
//    }

    /**
     * 删除article
     */
    @PreAuthorize("@ss.hasPermi('article:article:remove')")
    @Log(title = "article", businessType = BusinessType.DELETE)
    @DeleteMapping("/{articleIds}")
    public AjaxResult remove(@PathVariable Long[] articleIds)
    {
        return toAjax(articleService.deleteArticleByArticleIds(articleIds));
    }

    /**
     * 隐藏文章
     */
    @PreAuthorize("@ss.hasPermi('article:article:edit')")
    @Log(title = "article", businessType = BusinessType.UPDATE)
    @PutMapping("/hide/{articleId}")
    public AjaxResult hide(@PathVariable Long articleId)
    {
        return toAjax(articleService.hideArticle(articleId));
    }

    /**
     * 显示文章
     */
    @PreAuthorize("@ss.hasPermi('article:article:edit')")
    @Log(title = "article", businessType = BusinessType.UPDATE)
    @PutMapping("/show/{articleId}")
    public AjaxResult show(@PathVariable Long articleId)
    {
        return toAjax(articleService.showArticle(articleId));
    }

    /**
     * 批量隐藏文章
     */
    @PreAuthorize("@ss.hasPermi('article:article:edit')")
    @Log(title = "article", businessType = BusinessType.UPDATE)
    @PutMapping("/hideBatch")
    public AjaxResult hideBatch(@RequestBody Long[] articleIds)
    {
        int count = 0;
        for (Long articleId : articleIds) {
            count += articleService.hideArticle(articleId);
        }
        return toAjax(count);
    }

    /**
     * 按条件批量隐藏文章
     */
    @PreAuthorize("@ss.hasPermi('article:article:edit')")
    @Log(title = "文章", businessType = BusinessType.UPDATE)
    @PutMapping("/batchHideByCondition")
    public AjaxResult batchHideArticleByCondition(Article article)
    {
        // 根据条件查询文章列表
        List<Article> articles = articleService.selectArticleList(article);
        // 提取文章ID
        Long[] articleIds = articles.stream().map(Article::getArticleId).toArray(Long[]::new);
        // 批量隐藏文章
        return toAjax(articleService.batchHideArticle(articleIds));
    }

    /**
     * 按条件批量显示文章
     */
    @PreAuthorize("@ss.hasPermi('article:article:edit')")
    @Log(title = "文章", businessType = BusinessType.UPDATE)
    @PutMapping("/batchShowByCondition")
    public AjaxResult batchShowArticleByCondition(Article article)
    {
        // 根据条件查询文章列表
        List<Article> articles = articleService.selectArticleList(article);
        // 提取文章ID
        Long[] articleIds = articles.stream().map(Article::getArticleId).toArray(Long[]::new);
        // 批量显示文章
        return toAjax(articleService.batchShowArticle(articleIds));
    }

    /**
     * 逻辑删除article
     */
    @PreAuthorize("@ss.hasPermi('article:article:remove')")
    @PostMapping("/logicDelete/{articleIds}")
    public TableDataInfo logicRemove(@PathVariable Long[] articleIds) {
        List<RecoverStation> list= articleService.updateArticleDeletedStatus(articleIds);

        return getDataTable(list);
    }



    @PostMapping("file/saveFile")
    @Anonymous
    public AjaxResult saveFile(@RequestParam("file") MultipartFile file) {
        System.out.println("文章");
        if (file.isEmpty()) {
            return AjaxResult.error("文件为空");
        }
        try {
            // 获取文件名
            String fileName = UUID.randomUUID() + file.getOriginalFilename();
            // 文件存储路径
            File dest = new File(filePath + "/article/" + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            // 保存文件
            file.transferTo(dest);

            // 返回文件路径
            String fileUrl =filePath + "/article/" + fileName;
            return AjaxResult.success("上传成功", fileUrl);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("上传失败");
        }
    }

}
